<template>
  <div class="login">
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form">
      <h3 class="title">合记进销存管理系统</h3>
      <el-form-item prop="loginName">
        <el-input v-model="loginForm.loginName" type="text" size="large" auto-complete="off" placeholder="账号">
          <template #prefix><svg-icon icon-class="user" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="loginForm.password" type="password" size="large" auto-complete="off" placeholder="密码"
          @keyup.enter="handleLogin">
          <template #prefix><svg-icon icon-class="password" class="el-input__icon input-icon" /></template>
        </el-input>
      </el-form-item>
      <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
      <el-form-item style="width:100%;">
        <el-button :loading="loading" size="large" type="primary" style="width:100%;" @click.prevent="handleLogin">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="float: right;" v-if="register">
          <router-link class="link-type" :to="'/register'">立即注册</router-link>
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2025 .</span>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import useUserStore from '@/store/modules/user';
import { Engine } from "../public/engine/engine";
import { getDeviceId } from '../public/network/api.js';
import { Definition, DeviceType } from '../public/engine/common/definition';
import { login } from '../public/network/api.js';
import { NetworkParser } from '../public/network/communicationConverter';
import { Profile } from '../public/engine/user/profile';
import { ElMessage, ElMessageBox } from 'element-plus'
import { initRouteForJxc } from '../permission.js'
import { MerchantUiAction } from '../public/engine/uiAction/merchantUiAction.js';

export default {
  data() {
    return {
      loginForm: {
        loginName: "",
        password: "",
        rememberMe: false,
        uuid: ""
      },
      loginRules: {
        loginName: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
        password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
      },
      codeUrl: "",
      loading: false,
      captchaEnabled: true,
      register: false,
      redirect: undefined,
      userStore: useUserStore(),
      merchantUiAction: new MerchantUiAction(),
    };
  },

  created() {
    console.log('----> login created');
    this.initApp();

    if (window.location.href.indexOf('ltd.') > 0) {
      this.$router.push({ path: '/companyLogin' });
    }

    this.watchRoute();
    this.getCookie();
  },

  methods: {
    watchRoute() {
      this.$watch(
        () => this.$route,
        (newRoute) => {
          this.redirect = newRoute.query && newRoute.query.redirect;
        },
        { immediate: true }
      );
    },

    async handleLogin() {
      try {
        await this.$refs.loginRef.validate();
        console.log("Login valid:", true);

        this.loading = true;

        // 记住密码处理
        if (this.loginForm.rememberMe) {
          Cookies.set("loginName", this.loginForm.loginName, { expires: 30 });
          Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
          Cookies.set("rememberMe", this.loginForm.rememberMe, { expires: 30 });
        } else {
          Cookies.remove("loginName");
          Cookies.remove("password");
          Cookies.remove("rememberMe");
        }

        let profile = await this.merchantUiAction.getLoginData({
          ...this.loginForm,
          deviceType: Engine.deviceType,
          deviceId: Engine.deviceId,
        });

        if (profile) {
          Engine.setProfile(profile);

          if (Engine.profile.candidateOrg) {
            // 设置token
            Engine.storage.setStorageSync('token', Engine.profile.token);
            this.showMerchantCandidatePage(Engine.profile.candidateOrg);
          } else {
            ElMessage.warning("无商户信息")
          }
        }

        /*
        const res = await login({
          ...this.loginForm,
          deviceType: Engine.deviceType,
          deviceId: Engine.deviceId,
        });

        const parseResult = NetworkParser.parseNetworkResult(res, Profile.fromJson);

        if (parseResult && parseResult.data) {
          Engine.setProfile(parseResult.data);

          if (Engine.profile.candidateOrg) {
            // 设置token
            Engine.storage.setStorageSync('token', Engine.profile.token);
            this.showMerchantCandidatePage(Engine.profile.candidateOrg);
          } else {
            ElMessage.warning(content)
          }
        } else {
          console.log("parse error", parseResult);
          ElMessage.error('登录失败');
        }
        */
      } catch (error) {
        console.log("Login failed:", error);
      } finally {
        this.loading = false;
      }
    },

    getCookie() {
      const loginName = Cookies.get("loginName");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get("rememberMe");
      this.loginForm = {
        loginName: loginName === undefined ? this.loginForm.loginName : loginName,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };

      // todo 演示账户，记得删除
      /*
      if (!this.loginForm.loginName) {
        this.loginForm.loginName = "mtestuser001";
      }
      if (!this.loginForm.password) {
        this.loginForm.password = "123456"
      }
      */
    },

    async initApp() {
      console.log("-----> jxc app initApp");
      await Engine.init(true);
      this.loadAppAndDeviceData();
    },

    async loadAppAndDeviceData() {
      await Promise.all([
        this.getDeviceId(),
        this.getDeviceType(),
      ]);
    },


    async getDeviceId() {
      if (Engine.deviceId) {
        return;
      }
      const response = await getDeviceId();
      if (response.code === 200 && response.success === true && response.data) {
        const deviceId = response.data;
        Engine.deviceId = deviceId;
        Engine.saveDeviceIdData();
        console.log("got device id:", Engine.deviceId);
      } else {
        Engine.deviceId = Math.floor(Math.random() * 100000000).toString();
        console.log("got device failed set random num as id:", Engine.deviceId);
      }
    },

    // 获取设备类型
    async getDeviceType() {
      if (Definition.isWeb) {
        Engine.deviceType = DeviceType.web;
      } else {
        Engine.deviceType = DeviceType.desktop;
      }
    },

    async showMerchantCandidatePage(candidateMgr) {
      // 如果只有一个组织，直接进入应用界面。如果有多个组织，进入组织选择界面
      if (candidateMgr.dataList.length === 1) {
        try {
          const ret = await Engine.profile?.setOrg(candidateMgr.dataList[0]);

          if (ret) {
            console.log("failed to set org:", ret);
            ElMessageBox.alert("获取商户信息失败:" + ret, '错误', {
              confirmButtonText: '确定',
              type: 'error'
            });
            return;
          }
          else if (Engine.profile.permissionMgr) {
            this.userStore.jxcLogedIn(Engine.profile.token);
            // 设置路由
            initRouteForJxc(Engine.profile.permissionMgr);
          }
          else {
            console.log("failed to get permission info:", ret);
            ElMessage.error("未能获取获取商户授权信息");
          }



          if (Engine.profile?.org?.activePkg?.isExpired) {
            console.log("should go to charge page!");

            ElMessageBox({
              title: '套餐过期',
              message: '商户套餐已过期',
              showCancelButton: false,
              confirmButtonText: '确定',
              type: 'warning'
            }).then(() => {
              this.$router.push({
                path: '/charge',
                query: { org: encodeURIComponent(JSON.stringify(Engine.profile?.org)) }
              })
            }).catch(err => {
              console.error('对话框错误:', err)
            })

            return;
          }

          this.$router.push({ path: this.redirect.value || "/" });

        } catch (error) {
          console.error('Error while processing merchant candidate page: ', error);
        }
      } else {
        // todo 多个组织选择页面
        uni.reLaunch({
          url: '/pages/merchantCandidates/merchantCandidates?data=' + encodeURIComponent(JSON.stringify(candidateMgr.dataList))
        });
      }
    }
  }
}
</script>

<style lang='scss' scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 40px;

    input {
      height: 40px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 40px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 40px;
  padding-left: 12px;
}
</style>
